var specialRules=[];
function render(metadata,au) {
    var res = "<span id='dev_"+metadata.code+"'>";
    var requ = metadata.require == true ? " class='item-required' " : " style='display: none' ";
    if(au){
        res += "<label class='item-label' onclick='analyzeImg(\""+metadata.code+"\")'><span " + requ + ">*</span>" + metadata.name + "：</label>";
    }else{
        res += "<label class='item-label red' id='c"+metadata.code+"' onclick='analyzeImg(\""+metadata.code+"\")'><span " + requ + ">*</span>" + metadata.name + "：</label>";
        }
    var dynamic = "";
    var validType = metadata.require ? " required " : "";
    var a = ["", ""];
    switch (metadata.type) {
        case 'SELECTED':
            if(metadata.defaults == null && au != true){
                dynamic = "<select id='" + metadata.code + "' name='" + metadata.code + "' class='easyui-combobox' data-options='panelHeight:\"auto\",value:\"\",icons: [{ iconCls: \"icon-reload\", handler: function (e) { reloadMetadata(\""+metadata.code+"\") }}]' style='width:150px' prompt='--请选择--' " + validType + " >";
            }else{
                dynamic = "<select id='" + metadata.code + "' name='" + metadata.code + "' class='easyui-combobox' data-options='panelHeight:\"auto\",icons: [{ iconCls: \"icon-reload\", handler: function (e) { reloadMetadata(\""+metadata.code+"\") }}]'  style='width:150px' prompt='--请选择--' " + validType + " >";
            }
            break;
        case 'INPUT':
            dynamic = "<input id='" + metadata.code + "'name='" + metadata.code + "' type='text' class='easyui-textbox' style='width:150px' " + validType + "/>";
            break;
        case 'NUMBER':
            dynamic = "<input id='" + metadata.code + "'name='" + metadata.code + "' class='easyui-numberspinner' data-options='precision:" + metadata.scale + "' value='' style='width:150px;' " + validType + "/>";
            break;
        case 'BOOLEAN':
            var mcode1 = "qxz";
            if(au == true){
                mcode1 = mcode(metadata.defaults,metadata.values,"BOOLEAN");
            }
            if (mcode1 == true) {
                dynamic = "<select id='" + metadata.code + "'name='" + metadata.code + "' class='easyui-combobox' data-options='panelHeight:\"auto\"' style='width:150px;' " + validType + "><option value=''></option><option value='true' selected>是</option><option value='false'  >否</option></select>"
            } else if (mcode1 == false) {
                dynamic = "<select id='" + metadata.code + "'name='" + metadata.code + "' class='easyui-combobox' data-options='panelHeight:\"auto\"' style='width:150px;' " + validType + "><option value=''></option><option value='true'>是</option><option value='false' selected >否</option></select>"
            } else {
                dynamic = "<select id='" + metadata.code + "'name='" + metadata.code + "' class='easyui-combobox' data-options='panelHeight:\"auto\"' style='width:150px;' " + validType + "><option value=''></option><option value='true'>是</option><option value='false' >否</option></select>"
            }
            break;
        case 'MULTI':
            break;
        default:
            dynamic = "<input id='" + metadata.code + "'name='" + metadata.code + "' type='text' class='easyui-textbox' style='width:150px' " + validType + "/>";
    }
    if (metadata.type == "SELECTED") {
        if (metadata.values && metadata.values.length > 0) {
            dynamic += "<option></option>";
            for (var i = 0; i < metadata.values.length; i++) {
                if (au == true && metadata.defaults != null && metadata.values[i] == metadata.values[(metadata.defaults-1)]) {
                    //这里不给默认值，等规格排除事件执行完后在给默认值，先放到列表里
                    // dynamic += "<option selected>" + metadata.values[i] + "</option>";
                    propDefaultMap.set(metadata.code, metadata.values[i]);
                    dynamic += "<option>" + metadata.values[i] + "</option>";
                }else{
                    dynamic += "<option>" + metadata.values[i] + "</option>";
                }
            }
        }
        dynamic += "</select>";
        // dynamic += "<a class='l-btn-left l-btn-icon-left' style='width:22px;height: 24px' onclick='reloadMetadata(\""+metadata.code+"\")'><span class='l-btn-icon icon-reload'></span></a>";
    }
    if (metadata.type == "MULTI") {
        if(metadata.code == "04728"){
            for (var i = 0; i < metadata.values.length; i++) {
                var aa="zw";//指纹,密码,钥匙,刷卡,APP,人脸识别,微信,虹膜,指静脉,蓝牙
                if(metadata.values[i] == "密码"){
                    aa="mm";
                }else if(metadata.values[i] == "钥匙"){
                    aa="ys";
                }else if(metadata.values[i] == "刷卡"){
                    aa="sk";
                }else if(metadata.values[i] == "APP"){
                    aa = "app";
                }else if(metadata.values[i] == "人脸识别"){
                    aa = "rlsb";
                }
                else if(metadata.values[i] == "微信"){
                    aa = "wx";
                }
                else if(metadata.values[i] == "虹膜"){
                    aa = "hm";
                }
                else if(metadata.values[i] == "指静脉"){
                    aa = "zjm";
                }
                else if(metadata.values[i] == "蓝牙"){
                    aa = "ly";
                }
                dynamic += "<label style='padding:0 10px;'><input type='checkbox' name='" + metadata.code + "' value='" + metadata.values[i] + "' style='margin-right:5px; 'class='"+ aa+"'/>" + metadata.values[i] + "</label>";
            }
        } else{
            var multiData ="[";
            for (var i = 0; i < metadata.values.length; i++) {
                multiData += "{'id':'"+ metadata.values[i]+"', 'text': '"+metadata.values[i]+"'},"
            }
            multiData += "]";
            dynamic = "<select id='" + metadata.code + "' name='" + metadata.code + "' class='easyui-combobox combobox' style='width:150px;' " +
                "data-options=\"multiple:true," +
                "        valueField: 'id'," +
                "        textField: 'text'," +
                "        panelHeight:300," +
                "        prompt: '--请选择(多选)--'," +
                "        data:" + multiData +
                "        \""+validType+"></select>";
        }
    }
    res += dynamic;
    return res+"</span>";
}

//规格排除初始化
function propExcludeInit(){
    for (var i = 0; i < propExcludeList.length; i++) {
        addOnchange(propExcludeList[i]);
    }
}
//规格排除添加默认值
function propExcludeDefault(){
    propDefaultMap.forEach((value, key) => {
        $("#" + key).combobox("setValue", value);
    });
}
var propExcludeMap = new Map();  //<规格code,num>  num>0表示隐藏
function addOnchange(metadata){
    if (!metadata.propExclude || metadata.propExclude.length == 0) {
        return;
    }
    $("#"+metadata.code).combobox({
        onChange: function (n, o) {
            let propExclude = metadata.propExclude.replace(" ", "");
            let arr = propExclude.split(";");
            for (let i = 0; i < arr.length; i++) {
                let propContext = arr[i];
                if (!propContext) {
                    continue;
                }
                let prop = propContext.split(":");
                let value = prop[0];
                let exclude = prop[1].split(",");
                if (o == value) {
                    for (let j = 0; j < exclude.length; j++) {
                        let str = exclude[j].toString();
                        if (propExcludeMap.has(str)) {
                            let n = propExcludeMap.get(str) - 1;
                            propExcludeMap.set(str, n);
                        }
                    }
                }else if (n == value) {
                    for (let j = 0; j < exclude.length; j++) {
                        let str = exclude[j].toString();
                        if (propExcludeMap.has(str)) {
                            let n = propExcludeMap.get(str) + 1;
                            propExcludeMap.set(str, n);
                        }else {
                            propExcludeMap.set(str, 1);
                        }
                    }
                }
            }
            propExcludeMap.forEach((value, key) => {
                if (value > 0) {
                    $("#dev_"+key).hide();       //不占用页面位置
                    // $("#dev_" + key).css('visibility', 'hidden'); //占用页面位置
                }else {
                    $("#dev_"+key).show();
                    // $("#dev_" + key).css('visibility', 'visible');
                }
            });
        }
    })
}
var propExcludeList = [];  //规格排除的元素列表
var propDefaultMap = new Map();  //需要给默认值的规格排除元素列表
var allPropMap = new Map(); //所有的规格map
function generateContent(data,add,specialRules) {
    propExcludeList = [];
    propDefaultMap = new Map();
    allPropMap = new Map();
    specialRules=specialRules;
    var content = ["<div class='box'>"];
    for (var i = 0; i < data.length; i++) {
        allPropMap.set(data[i].code, data[i]);
        if(data[i].type=='SELECTED'&&data[i].propExclude){
            propExcludeList.push(data[i]);
        }

        // if (i != 0 && i % 3 == 0) {
        //     content.push("</div><div class='box' style='margin: 10px 0' >");
        //
        // }
        // content.push(render(data[i], add));
        if (null != data[i].coordinateX) {
            if(i==0){
                content.push(render(data[i], add));
            }else{
                if (data[i].coordinateX - data[i - 1].coordinateX != 0) {
                    content.push("</div><div class='box' style='margin: 10px 0' >");
                    content.push(render(data[i], add));
                } else if(data[i].coordinateX == 1 &&null ==data[i-1].coordinateX ){
                    content.push("</div><div class='box' style='margin: 10px 0' >");
                    content.push(render(data[i], add));
                }else {
                    content.push(render(data[i], add));
                }
            }
            // if (data[i].coordinateX == 1 && i==0) {
            //     content.push(render(data[i], add));
            // } else
        }else{
            if (i != 0 && i % 3 == 0) {
                content.push("</div><div class='box' style='margin: 10px 0' >");

            }
            content.push(render(data[i], add));
        }
    }
    content.push('</div>');
    // console.log(content)
    return content.join("");
}

function renderComponent(metadata) {
    var res = "";
    var dynamic = "";
    switch (metadata.type) {
        case 'SELECTED':
            dynamic = "<select name='" + metadata.code + "' class='easyui-combobox' data-options='panelHeight:\"auto\"' style='width:100px;margin-left:5px;'>";
            break;
        case 'NUMBER':
        case 'INPUT':
            dynamic = "<input name='" + metadata.code + "' prompt='" + metadata.name + "' type='text' class='easyui-textbox' style='width:100px;margin-left:5px;'/>";
            break;
        case 'BOOLEAN':
            dynamic = "<select name='" + metadata.code + "' class='easyui-combobox' data-options='panelHeight:\"auto\"' style='width:100px;margin-left:5px;'><option value='' selected>" + metadata.name + "</option><option value='true'>是</option><option value='false'>否</option></select>"
            break;
        case 'MULTI':
            dynamic = "";
            break;
        default:
            dynamic = "<input name='" + metadata.code + "' type='text' class='easyui-textbox' style='width:100px;margin-left:5px;'/>";
    }
    if (metadata.type == "SELECTED") {
        if (metadata.values && metadata.values.length > 0) {
            dynamic += "<option value=''>" + metadata.name + "</option>";
            for (var i = 0; i < metadata.values.length; i++) {
                dynamic += "<option>" + metadata.values[i] + "</option>";
            }
        }
        dynamic += "</select>";
    }
    if (metadata.type == "MULTI") {
        for (var i = 0; i < metadata.values.length; i++) {
            dynamic += "<label style='padding:0 10px;'><input type='checkbox' name='" + metadata.code + "' value='" + metadata.values[i] + "' style='margin-right:5px;'/>" + metadata.values[i] + "</label>";
        }
    }
    res += dynamic;
    return res;
}

function mcode(defaults,values,type) {
    var mvalue = "";
    if(values == null ||values.length == 0){
        if(defaults == 1){
            mvalue=true;
        }else if(defaults == 2){
            mvalue=false;
        }else{
            mvalue = "qxz"
        }
    }else {
        defaults=defaults-1;
        if(values[defaults] == "是" || values[defaults] == "有"){
            mvalue=true;
        }else if(values[defaults] == "否" || values[defaults] == "无"){
            mvalue=false;
        }else{
            mvalue = "qxz"
        }
    }

    /*switch (f) {
        case '04202':
            mvalue = true;
            break;
        case '04203':
            mvalue = true;
            break;
        case '04204':
            mvalue = true;
            break;
        case '04205':
            mvalue = false;
            break;
        case '04208':
            mvalue = false;
            break;
        case '04211':
            mvalue = true;
            break;
        case '04217':
            mvalue = false;
            break;
        case '04221':
            mvalue = false;
            break;
        case '04212':
            mvalue = true;
            break;
        case '04213':
            mvalue = true;
            break;
        case '04214':
            mvalue = true;
            break;
        case '04215':
            mvalue = true;
            break;
        case '04216':
            mvalue = true;
            break;
        case '04218':
            mvalue = true;
            break;
        case '04219':
            mvalue = true;
            break;
        case '04221':
            mvalue = true;
            break;
        case '04222':
            mvalue = true;
            break;
        case '04223':
            mvalue = true;
            break;
        case '04224':
            mvalue = true;
            break;
        case '04709':
            mvalue = true;
            break;
        case '04721':
            mvalue = true;
            break;
        case '04742':
            mvalue = true;
        break;
        default:
            mvalue = "qxz"
    }*/

    return mvalue;
}

//特殊品类规格需要单独处理
function specialProp(){
    /**
     * 针对智能门锁进行关联项
     */
    $(".zw").change(function(a) {
        if($(".zw").prop('checked')){
            $("#04774").combobox("setValue","是");
            // alert("选中");
            //当前为选中状态
        }else {
            $("#04774").combobox("setValue","否");
            // alert("未选中");
            //当前为不选中状态
        }
    });
    $(".mm").change(function(a) {
        if($(".mm").prop('checked')){
            $("#04775").combobox("setValue","是");
            //当前为选中状态
        }else {
            $("#04775").combobox("setValue","否");
            //当前为不选中状态
        }
    });

    $(".ys").change(function(a) {
        if($(".ys").prop('checked')){
            $("#04776").combobox("setValue","是");
            //当前为选中状态
        }else {
            $("#04776").combobox("setValue","否");
            //当前为不选中状态
        }
    });
    $(".sk").change(function(a) {
        if($(".sk").prop('checked')){
            $("#04777").combobox("setValue","是");
            //当前为选中状态
        }else {
            $("#04777").combobox("setValue","否");
            //当前为不选中状态
        }
    });
    $(".app").change(function(a) {
        if($(".app").prop('checked')){
            $("#04778").combobox("setValue","是");
            //当前为选中状态
        }else {
            $("#04778").combobox("setValue","否");
            //当前为不选中状态
        }
    });
    $(".rlsb").change(function(a) {
        if($(".rlsb").prop('checked')){
            $("#04779").combobox("setValue","是");
            //当前为选中状态
        }else {
            $("#04779").combobox("setValue","否");
            //当前为不选中状态
        }
    });
    $(".wx").change(function(a) {
        if($(".wx").prop('checked')){
            $("#04780").combobox("setValue","是");
            //当前为选中状态
        }else {
            $("#04780").combobox("setValue","否");
            //当前为不选中状态
        }
    });
    $(".hm").change(function(a) {
        if($(".hm").prop('checked')){
            $("#04781").combobox("setValue","是");
            //当前为选中状态
        }else {
            $("#04781").combobox("setValue","否");
            //当前为不选中状态
        }
    });
    $(".zjm").change(function(a) {
        if($(".zjm").prop('checked')){
            $("#04782").combobox("setValue","是");
            //当前为选中状态
        }else {
            $("#04782").combobox("setValue","否");
            //当前为不选中状态
        }
    });
    $(".ly").change(function(a) {
        if($(".ly").prop('checked')){
            $("#04783").combobox("setValue","是");
            //当前为选中状态
        }else {
            $("#04783").combobox("setValue","否");
            //当前为不选中状态
        }
    });
    //针对按摩仪
    $("#05213").combobox({
        onSelect: function (a) {
            if(a.value =="足浴盆"){
                var fruits = ["腿部", "脚部"]
                $("#05220").combobox("setValues",fruits);
            }else{
                $("#05220").combobox("setValues","");
            }
            debugger;
        }
    });
}

function reloadMetadata(metadataCode) {
    $.ajax({
        url:config.url+"/categoryMetadata/getMetadataUnderCategory?categoryCode="+categoryCode,
        type:'get',
        xhrFields:{withCredentials:true},
        beforeSend: function () {
            $.messager.progress({
                title: "请稍等",
                interval: 20,
                text: "数据加载中..."
            });
        },
        complete: function () {
            $.messager.progress("close");
        },
        success:function (data) {
            //规格数据填充
            for (var i = 0; i < data.length; i++) {
                let metadata = data[i];
                var values = [{"name": "",code:""}];
                if (metadata.code == metadataCode) {
                    metadata.values.forEach(function (v) {
                        values.push({"text": v,"value":v});
                    });
                    $("#"+metadataCode).combobox({
                        "textField": "text",
                        "valueField": "value",
                        "panelHeight": 150,
                        "prompt": "--请选择--",
                        "data": values,
                        onChange: function (newValue, oldValue) {
                        }
                    });
                    return;
                }

            }

        }
    });

}

function initSeries(categoryCode,brandId,seriesCode) {
    if (categoryType != 2) {
        return;
    }

    var dtd = $.Deferred();
    let brandCode = $("#"+brandId).combobox("getValue");
    if (!brandCode) {
        return;
    }
    $.ajax({
        url: config.url + "/series/getAll",
        type: "get",
        data: {categoryCode:categoryCode,brandCode:brandCode},
        xhrFields: {withCredentials: true},
        async:false,
        success: function (data) {
            if (data.code == 200) {
                $('#seriesTo3cCode').combobox('loadData', {});//清空option选项
                let msg = data.msg;
                msg.unshift({"name": "", "code": ""});
                $("#seriesTo3cCode").combobox({
                    "textField": "name",
                    "valueField": "code",
                    "panelHeight": 150,
                    "prompt": "--请选择--",
                    "data": msg,
                    onChange: function (newValue, oldValue) {
                    }
                });
                if(seriesCode){
                    $('#seriesTo3cCode').combobox("select", seriesCode);
                }
            }
            dtd.resolve();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {

        }
    });
    return dtd.promise();
}

/***********************型号网址图片识别相关功能****************************/
/***********************型号网址图片识别相关功能****************************/
/***********************型号网址图片识别相关功能****************************/
function tzwy() {
    var  wz=$("#description").tagbox('getValues');
    if(wz != null && wz !=""){
        wz.forEach(function(v){
            window.open(v);
            // document.getElementById("tzwy").href = v;
        });
    }
}

function copyUrl(){
    var  url=$("#description").textbox('getValue');
    var flag = copyText(url);
    $.messager.show({
        title: '提示',
        msg: flag?"网址复制成功":"网址复制失败",
        timeout: 500,
        showType: 'show'
    });
}

function showProp(itemProperties) {
    if (!itemProperties) {
        return
    }

    $("#propTable").empty();
    var content = "";

    for (let i = 0; i < itemProperties.length; i++) {
        if ((i + 1) % 3 == 1) {
            content = "<tr><td class='propTd'><b>" + itemProperties[i].name+":</b>"+itemProperties[i].value+"</td>";
        }else if ((i + 1) % 3 == 0) {
            content += "<td class='propTd'><b>" + itemProperties[i].name+":</b>"+itemProperties[i].value + "</td></tr>";
            $("#propTable").append(content);
        }else {
            content += "<td class='propTd'><b>" +itemProperties[i].name+":</b>"+itemProperties[i].value + "</td>";
            if ((i + 1) == itemProperties.length) {
                content += "</tr>";
                $("#propTable").append(content);
            }
        }
    }
    $("#propDetail").show();

            }

function showImage() {
    if ($('#jdImg').is(':hidden')) {
        //获取请求地址
        let reqUrl = getReqUrl();
        if(!reqUrl){
            return;
        }
        //请求图片
        reqImgUrl(reqUrl);
    } else {
        $("#jdImg").empty();
        $("#jdImg").hide();
        $("#imgAnalyzeDiv").hide();
        $("#addModelNone").dialog({
            width: "1600",
            left: '60px'
        }).dialog("open");
    }
}

function getReqUrl(){
    var skus = $("#description").tagbox("getValues");
    if (!skus) {
        $.messager.alert("提示", "请输入网址", "info");
        return;
    }
    var skuid = "";
    var reqUrl;
    for (const sku of skus) {
        if (sku.match("jd.com")) {
            //京东
            skuid = sku.replace(/[^0-9]/ig, "");
            reqUrl = "/jdAffiliatedImage_detail/" + skuid + "/";
            break;
        } else if (sku.match("kwaixiaodian")) {
            //快手:https://app.kwaixiaodian.com/merchant/shop/detail?id=21446369569571
            skuid = sku.replace(/[^0-9]/ig, "");
            reqUrl = "/ksdy/server/img?token=kjasbdls15asw&type=1&itemId=" + skuid;
            break;
        } else if (sku.match("jinritemai")) {
            //抖音:https://haohuo.jinritemai.com/ecommerce/trade/detail/index.html?origin_type=old_h5&id=3663412991954680520&origin_type=3002070010
            skuid = sku.match(/id=(\d+)/)[1];
            reqUrl = "/ksdy/server/img?token=kjasbdls15asw&type=2&itemId=" + skuid;
            break;
        } else if (sku.match("tmall.com")) {
            //天猫
            skuid = sku.replace(/[^0-9]/ig, "");
            reqUrl = "/taoTmdemo/?itemId=" + skuid;
            break;

        } else if (sku.match("taobao.com")) {
            //天猫
            skuid = sku.replace(/[^0-9]/ig, "");
            reqUrl = "/taoTmdemo/?itemId=" + skuid;
            break;

        }
    }
    if (!skuid) {
        $.messager.alert("提示", "无有效网址", "error");
        return;
    }
    return reqUrl;
}

function reqImgUrl(reqUrl){
    if (reqUrl.match("taoTmdemo")) {
        window.open(window.config.jdUrl + reqUrl);
    } else {
        $.ajax({
            url: window.config.jdUrl + reqUrl,
            type: "get",
            dataType: "json",
            xhrFields: {
                withCredentials: true
            },
            beforeSend: function () {
                $.messager.progress({
                    title: "请稍等",
                    interval: 30,
                    text: "图片查询中..."
                });
            },
            complete: function () {
                $.messager.progress("close");
            },
            success: function (data) {
                if (data.code != 200) {
                    $.messager.alert("提示", "查询失败!" + data.msg, "error");
                    return
                }
                openImg(data.msg.detail_imgs);
                showProp(data.msg.product_format);
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.messager.progress("close");
            }
        });
    }
}

function openImg(imgs) {
    var dtd = $.Deferred();
    $("#jdImg").empty();
    $("#jdImg").show();
    for (let i = 1; i <= imgs.length; i++) {
        var imgId = "img" + i;
        $("#jdImg").append("<img class='modelImg' id='" + imgId + "' src='" + imgs[i-1] + "'>");
        imgSizeInit(imgId);
    }
    $("#imgAnalyzeDiv").show();
    return dtd.promise();
}


var imgAnalyzeData = [];    //所有图片识别的信息
function imageAnalyze(againFlag) {
    var skus = $("#description").tagbox("getValues");
    if(!skus){
        $.messager.alert("提示", "请输入京东网址", "info");
        return;
    }
    var jdUrl;
    var tmallUrl;
    for (const sku of skus) {
        if(sku.match("jd.com")){
            // skuId = sku.replace(/[^0-9]/ig,"");
            jdUrl = sku;
            continue;
        }else if(sku.match("tmall.com")){
            // skuId = sku.replace(/[^0-9]/ig,"");
            tmallUrl = sku;
            continue;
        }
    }
    if (!jdUrl&&!tmallUrl) {
        $.messager.alert("提示", "无有效京东/天猫网址", "info");
        return;
    }
    imgAnalyzeData = [];
    $.ajax({
        url: config.url +"/workshop/imgAnalyze",
        type: "Post",
        xhrFields: {withCredentials: true},
        data:{jdUrl: jdUrl,tmallUrl:tmallUrl, againFlag: againFlag},
        dataType: "json",
        beforeSend: function () {
            $.messager.progress({
                title: "请稍等",
                interval: 30,
                text: "图片识别中..."
            });
        },
        complete: function () {
            $.messager.progress("close");
        },
        success: function (data) {
            if (data.code != 200) {
                $.messager.alert("提示", data.msg, "error");
                return;
            }
            if(data.data.tmallimagess){
                showProp(data.data.tmallimagess.itemProperties);
            }
            if (data.data.imgAnalyzeInfos) {
                imgAnalyzeData = data.data.imgAnalyzeInfos;
                //显示图片
                openImg(data.data.imgs);
                $.messager.alert("提示", data.msg, "info");
            }else {
                $.messager.alert("提示", "没有此sku图片识别信息", "info");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.messager.progress("close");
        }
    });
}

var analyzeContent = {};    //识别到内容的具体信息
//点击规格名称识别
function analyzeImg(categoryMetadataCode) {
    if (!categoryMetadataCode) {
        $.messager.alert("提示", "规格码为空", "error");
        return;
    }
    if (!imgAnalyzeData || imgAnalyzeData.length <= 0) {
        $.messager.alert("提示", "未查询到图片识别内容，请点击识别按钮", "error");
        return;
    }
    $.ajax({
        url: window.config.url+"/categoryMetadata/byCode/"+categoryMetadataCode,
        type: "get",
        dataType: "json",
        xhrFields:{withCredentials:true},
        success: function (data) {
            if (data.code != 200) {
                $.messager.alert("提示", data.msg, "error");
                return;
            }
            let analyzeTexts = data.msg.analyzeTexts;
            if (!analyzeTexts || analyzeTexts.length <= 0) {
                $.messager.alert("提示", "请添加识别内容", "info");
                return;
            }
            var cmp=data.msg;
            var selectContent = []; //识别到的内容
            analyzeContent = {};
            analyzeTexts.forEach(function(v){
                queryContent(v, selectContent);
            });
            propTableSearch(analyzeTexts);
            imgAnalyzeSelect(selectContent);
            // if(selectContent && selectContent.length==1){
            //     //如果识别出来一个需要自动赋值aaaaaaaaaaaaaaaaaaa
            //     if(cmp.type=="MULTI" ||cmp.type=="SELECTED"){
            //         var hs="";
            //         if(cmp.values){
            //             cmp.values.forEach(function(v){
            //                 if(selectContent[0].value.indexOf(v) != -1){
            //                     hs=v;
            //                 }
            //             });
            //         }
            //         if(hs){
            //             $("#"+categoryMetadataCode).combobox("select", hs);
            //         }else{
            //             $("#"+categoryMetadataCode).combobox("select", "是");
            //         }
            //         if(specialRules && specialRules.length>0){
            //             alert("可以拿到恭喜恭喜")
            //         }
            //     }
            // }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            $.messager.progress("close");
        }
    });
}

//根据关键字去图片里找内容
function queryContent(content,selectContent) {
    content = content.replace(/\s*/g, "").toUpperCase(); //清除空格

    for (let i = 0; i < imgAnalyzeData.length; i++) {
        let imgTextDetections = imgAnalyzeData[i].imgTextDetections; //每一张图片信息
        if(imgTextDetections){
            for (let j = 0; j < imgTextDetections.length; j++) {    //每条信息
                let detectedText = imgTextDetections[j].detectedText;
                if (detectedText && detectedText.replace(/\s*/g, "").toUpperCase().indexOf(content) != -1) {
                    let code = (i+1) + "&" + j;     //key 格式 ：图片位置（1开始）+&+文字所在图片位置（0开始）
                    if (!analyzeContent[code]) {
                        analyzeContent[code] = imgTextDetections[j];
                        //判断选择框里是否有同样的数据
                        var repeatNum = 0;  //重复次数
                        var text;
                        while (true) {
                            var repeatFlag = false;
                            text = detectedText;
                            if (repeatNum > 0) {
                                text = ("<span style='color: red'>(" + repeatNum + ")</span>" + detectedText);
                            }
                            selectContent.forEach(function (v) {
                                if (v.value == text) {
                                    repeatNum++;
                                    repeatFlag = true;
                                }
                            });
                            if (!repeatFlag) {  //没有重复可以退出了
                                break;
                            }
                        }
                        var select= {"code":code, "value": text};
                        selectContent.push(select);

                    }
                }
            }
        }
    }
}

//根据选择的内容跳转到图片指定位置
function imgAnalyzeSelect(selectContent) {
    $(".img_content").remove();
    $("#imgAnalyzeSelect").combobox('clear');   //清除选中值
    $("#imgAnalyzeSelect").combobox('loadData', {});    //清空下拉框内容
    if (selectContent && selectContent.length > 0) {
        $("#imgAnalyzeSelect").combobox({
            "textField": "value",
            "valueField": "code",
            "panelHeight": 150,
            "prompt": "--请选择--",
            "data": selectContent,
            onChange: function (newValue, oldValue) {
                //跳转到指定图片位置
                if (newValue) {
                    let split = newValue.split("&");
                    //如果是规格识别  0是图片位置  1是图片里的某个位置的信息
                    //如果是型号识别  0是型号码  1是型号名，图片位置隐藏在识别文字的尾部，使用&+index拼接
                    let imgNum = split[0];
                    var imgTextDetection;
                    if (imgNum.length == 8) {
                        imgTextDetection = imgAnalyzeModels[newValue];
                        imgNum = imgTextDetection.index;
                    } else {
                        imgTextDetection = analyzeContent[newValue];
                    }
                    if (!imgSizeProp["img1"]) {
                        return;
                    }

                    let imgSizePropElement = imgSizeProp["img" + imgNum];    //获取所在图片缩放的比例
                    let contentHeight = imgTextDetection.height * imgSizePropElement;
                    let contentX = imgTextDetection.x * imgSizePropElement;
                    let contentY = imgTextDetection.y * imgSizePropElement;

                    //计算文字距离顶部的距离=前面所有图片的高度+contentY
                    var contentTop = 0;
                    for (let i = 1; i < imgNum; i++) {
                        contentTop += $("#img" + i).height();
                    }
                    contentTop += contentY;

                    // console.log('contentHeight: ', contentHeight);
                    // console.log('contentX: ', contentX);
                    // console.log('contentY: ', contentY);

                    var img_content = "<div class='img_content' style='";
                    img_content += "font-size: " + Math.round(contentHeight > 20 ? contentHeight - 10 : contentHeight) + "px;";
                    img_content += "top:" + Math.round(contentTop) + "px;";
                    img_content += "left:" + Math.round(contentX) + "px'>";
                    img_content += imgTextDetection.detectedText + "</div>";
                    $("#jdImg").append(img_content);

                    //计算滑动的高度=文字的高度 -180
                    var slideHeight = 0;
                    if (contentTop >= 180) { //让内容显示在距离顶部180px的位置
                        slideHeight = contentTop-180; //滑动的总距离
                    }

                    $("#jdImg").animate({scrollTop: slideHeight}, 300);
                    // $.when().done(function () {
                        // $("#img_content").text(imgTextDetection.detectedText);
                        // $("#img_content").css('font-size', contentHeight > 20 ? contentHeight - 10 : contentHeight);
                        // $("#img_content").css('top', slideHeight);
                        // $("#img_content").css('width', imgTextDetection.width* imgSizePropElement);
                        // $("#img_content").css('left', contentX);  //760=jdImg的left
                        // $("#img_content").show();
                    // });
                }
            },
        });
        //默认选中第一个,型号无法默认，因为初始化imgSizeProp的加载机制在最后
        $("#imgAnalyzeSelect").combobox('select', selectContent[0].code);

    }
}

function cleanAnalyze() {
    $(".img_content").remove();
}
function againAnalyze() {
    $.messager.confirm("提示", "您确定要重新识别吗?", function (r) {
        if (r) {
            imageAnalyze(true);
        }
    });
}

//初始化图片显示大小
var imgSizeProp = {};   //图片缩放比例
function imgSizeInit(id) {
    var dtd = $.Deferred();
    var _w = $("#jdImg").width();//获取div的宽度
    var realWidth;//真实的宽度
    var realHeight;//真实的高度

    var url = $("#"+id).attr("src");
    // var url = "https://img.alicdn.com/imgextra/i2/2207779148542/O1CN014K3hyq2CyHoex4Ee3_!!2207779148542.jpg";
    //这里做下说明，$("<img/>")这里是创建一个临时的img标签，类似js创建一个new Image()对象！
    $("<img/>").attr("src", url).load(function () {  //好像最后才加载此事件
        /*
        如果要获取图片的真实的宽度和高度有三点必须注意
        1、需要创建一个image对象：如这里的$("<img/>")
        2、指定图片的src路径
        3、一定要在图片加载完成后执行如.load()函数里执行
        */
        realWidth = this.width;
        realHeight = this.height;
        // console.log('我的宽度是: ', realWidth);
        // console.log('我的高度是: ', realHeight);
        //如果真实的宽度大于浏览器的宽度就按照100%显示
        if (realWidth >= _w) {
            imgSizeProp[id] = _w / realWidth;
            $("#"+id).css("width", "100%").css("height", "auto");
        }else { //如果小于浏览器的宽度按照原尺寸显示
            imgSizeProp[id] = 1;
            $("#"+id).css("width", realWidth + 'px').css("height", realHeight + 'px');
        }
    });
    return dtd.promise();
}
function imgSearch(value){
    if (!value) {
        $.messager.alert("提示", "请输入查找内容", "info");
        return;
    }
    var content = [];
    content.push(value);
    propTableSearch(content);
    var selectContent = []; //识别到的内容
    analyzeContent = {};
    queryContent(value,selectContent);
    imgAnalyzeSelect(selectContent);
    $("#imgAnalyzeSelect").combogrid('textbox').focus(); //光标放到imgAnalyzeSelect
    $("#imgModelConfirm").hide();
}

//对规格里的数据进行高亮显示
function propTableSearch(content) {
    if (!content) {
        return;
    }
    var propTr = $("#propTable tr");
    if (!propTr) {
        return;
    }
    propTr.each(function (i) {                   // 遍历 tr
        $(this).children('td').each(function (j) {  // 遍历 tr 的各个 td
            let css = $(this).children("b").css("color");
            //还原原高亮显示的td
            if (css == "rgb(255, 0, 0)") {
                let tdValue = $(this).text();
                let indexOf = tdValue.indexOf(":");
                let s1 = tdValue.substring(0, indexOf);
                let s2 = tdValue.substring(indexOf + 1);
                $(this).html("<b >" + s1 + ":</b>" + s2);
            }
            for (var val of content) {
                if ($(this).text().replace(/\s*/g, "").toUpperCase().indexOf(val.replace(/\s*/g, "").toUpperCase()) != -1) {
                    $(this).html("<b style='color: red'>" + $(this).text() + "</b>");
                    // console.log(("第" + (i + 1) + "行，第" + (j + 1) + "个td的值：" + $(this).text() + "。"));
                    break;
                }
            }
        });
    });

}
function toggleSellingPoints() {
    var wrapper = $("#sellingPointWrapper");
    var button = $("#toggleSellingPointBtn");

    if (wrapper.is(":visible")) {
        wrapper.hide();
        button.linkbutton({text: '展开'});
    } else {
        wrapper.show();
        button.linkbutton({text: '收起'});
    }
}

function generateSellingPointWrapper(){
    //判断是否已近生成卖点数据
    if ($("#sellingPointWrapper").children().length > 0) {
        return;
    }
    for (let i = 1; i < 10; i++) {
        $("#sellingPointWrapper").append("<div style='margin-bottom:10px;'>" +
            "<label class='item-label'>卖点" + i + "：</label>\n" +
            "<input name='sellingPoint" + i + "' class='easyui-textbox' value='' style='width:482px;'/>" +
            "</div>");
    }
    $.parser.parse($("#sellingPointWrapper"));
}
/**********************************型号网址相关功能***************************************/
function defaultMetadataValue(id){
    var msg = "您确定将所有空白必填项填入默认值-1吗? ";
    $.messager.confirm("提示", msg, function (r) {
        var requiredProp = $("#"+id+" [required]");
        for (let i = 0; i < requiredProp.length; i++) {
            let prop = requiredProp[i];
            let value = prop.value;
            if (value) {
                //如果有值不作修改，多选获取不到
                continue;
            }
            let metadata = allPropMap.get(prop.id);
            // console.log(prop.id+"--"+metadata.name);
            // console.log(metadata.values);
            if (!metadata) {
                continue;
            }
            // 多选单独处理
            if (metadata.type == "MULTI") {
                let multiValue = $("#" + prop.id).combobox('getValue');
                if (multiValue != undefined && multiValue != "") {
                    continue;
                }
            }
            if (metadata.type == "SELECTED" || metadata.type == "BOOLEAN" || metadata.type == "MULTI") {
                if (metadata.values.includes("未标注")) {
                    $("#" + prop.id).combobox("setValue", "未标注");
                }
            }else if(metadata.type == "NUMBER"){
                $("#" + prop.id).textbox("setValue", "-1");
            }else if(metadata.type == "INPUT"){
                $("#" + prop.id).textbox("setValue", "未标注");
            }
        }
    });
}
